package com.bawei.module_mine.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.adapter.CommonVDBRecyclerAdapter
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.FragmentMineBinding
import com.bawei.module_mine.databinding.LayoutToolsItemBinding
import com.bawei.module_mine.ui.mine.MineViewModel
import com.bawei.myclub.base.mvvm.view.BaseFragment
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.handleCoroutineException
import javax.inject.Inject

@Route(path = Router.Ui.MineFragment)
@AndroidEntryPoint
class MineFragment @Inject constructor() : BaseFragment<MineViewModel, FragmentMineBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_mine
    override val mViewModel: MineViewModel by viewModels()

    companion object {
        const val CLUB_MGR = "club_mgr"
        const val MSG_CENTER = "msg_center"
        const val STOLEN = "stolen"
        const val APP_SHARE = "share"
        const val HELP_CENTER = "help_center"
        const val WIKI = "wiki"
        const val CUSTOMER = "customer"
        const val JOIN = "join"
        const val SETTINGS = "settings"

        const val STORE_SEARCH = "store_search"
        const val BOOKING_DRV = "booking_drv"
        const val RESCUE = "rescue"
        const val CARE_SERVICE = "care_service"
        const val FIX_ONLINE = "fix_online"

        const val MALL_ORDER = "store_search"
        const val MALL_COUPON = "mall_coupon"
        const val CYCLONE_BEAN = "cyclone_bean"
        const val MALL_ACCOUNT = "mall_account"

        const val ROUTE = "route"


        const val MY_CAR = "my_car"
        const val DRIVING_DATA = "driving_data"
        const val DRIVING_GROUP = "driving_group"
        const val MY_ACTIVITY = "my_activity"
    }

    /** 账户服务 */
    private val mMallTabItem by lazy {
        mutableListOf(
            TabItem(MALL_ORDER, "订单", R.mipmap.icon_mall_order, false),
            TabItem(MALL_COUPON, "优惠券", R.mipmap.icon_mall_coupon, false),
            TabItem(CYCLONE_BEAN, "龙豆兑换", R.mipmap.icon_cyclone_bean, false),
            TabItem(MALL_ACCOUNT, "我的账户", R.mipmap.icon_mall_favorites, false),
        )
    }
    private val mMallAdapter by lazy {
        ToolAdapter(mMallTabItem) {

        }
    }

    /** 爱车服务 */
    private val mMyCarTabItem by lazy {
        mutableListOf(
            TabItem(MY_CAR, "添加爱车", R.mipmap.icon_add_motor, false),
            TabItem(MY_ACTIVITY, "我的活动", R.mipmap.icon_my_activity, false),
            TabItem(DRIVING_GROUP, "骑行组队", R.mipmap.icon_drive_group, false),
        )
    }
    private val myCarAdapter by lazy {
        ToolAdapter(mMyCarTabItem) {

        }
    }

    /** 门店服务 */
    private val mServiceTabItem by lazy {
        mutableListOf(
            TabItem(STORE_SEARCH, "寻找门店", R.mipmap.icon_search_store, false),
            TabItem(BOOKING_DRV, "预约试驾", R.mipmap.icon_booking, false),
            TabItem(RESCUE, "一键救援", R.mipmap.icon_rescue, false),
            TabItem(CARE_SERVICE, "保养服务", R.mipmap.icon_care_service, false),
            TabItem(FIX_ONLINE, "在线报修", R.mipmap.icon_fix_online, false),
        )
    }
    private val mServiceAdapter by lazy {
        ToolAdapter(mServiceTabItem) {

        }
    }

    /** 常用工具 */
    private val mToolTabItem by lazy {
        mutableListOf(
            TabItem(CLUB_MGR, "俱乐部管理", R.mipmap.icon_club_management, false),
            TabItem(WIKI, "知识库", R.mipmap.icon_menu_wiki, false),
            TabItem(STOLEN, "失窃上报", R.mipmap.icon_stolen_applications, false),
            TabItem(APP_SHARE, "APP分享", R.mipmap.icon_app_share, false),
            TabItem(HELP_CENTER, "帮助中心", R.mipmap.icon_help, false),
            TabItem(CUSTOMER, "联系客服", R.mipmap.icon_customer, false),
            TabItem(JOIN, "招商加盟", R.mipmap.icon_commercial_join, false),
            TabItem(SETTINGS, "设置中心", R.mipmap.icon_settings, false),
        )
    }
    private val mToolAdapter by lazy {
        ToolAdapter(mToolTabItem) {

        }
    }

    private var mInitView = false


    private var mAdapter: CommonVDBRecyclerAdapter<TabItem, LayoutToolsItemBinding>? = null

    private fun initAdapter(onItemClick: (id: String) -> Unit) {
        if (mAdapter == null) {
            mAdapter = object : CommonVDBRecyclerAdapter<TabItem, LayoutToolsItemBinding>(
                R.layout.layout_tools_item,
                mToolTabItem
            ) {
                override fun convert(
                    holder: BaseDataBindingHolder<LayoutToolsItemBinding>,
                    item: TabItem
                ) {
                    holder.dataBinding?.item = item
                    holder.dataBinding?.vRedPoint?.visibility =
                        if (item.hasNew) View.VISIBLE else View.GONE
                }
            }
            mBinding.rvTool.adapter = mAdapter
            mAdapter!!.setOnItemClickListener { adapter, view, position ->
                onItemClick.invoke(mToolTabItem[position].id)
            }

        } else {
            mAdapter?.setNewInstance(mToolTabItem)
        }
    }

    override fun initView() {
        initShowView()
        mBinding.rvService.adapter = mServiceAdapter
        mBinding.rvMall.adapter = mMallAdapter
        mBinding.rvMyCar.adapter = myCarAdapter
        mBinding.rvTool.adapter = mToolAdapter
    }


    override fun onStart() {
        super.onStart()
        //token为空-重置页面
        if (AuthMMKV.access_token.isEmpty()) {
            onNotLogin()
        }

    }

    private fun initShowView() {
        if (AuthMMKV.access_token.isEmpty()) {
            onNotLogin()
        } else {
            onLogin()
        }
    }

    override fun initListener() {



        mBinding.btnLogin.setOnClickListener {
            // 去登录
            ARouter.getInstance().build(Router.Ui.LoginActivity).withTransition(
                com.bawei.lib_common.R.anim.bottom_in,
                com.bawei.lib_common.R.anim.fab_out
            ).navigation()
        }
    }

    override fun initData() {
        if (AuthMMKV.hasLogin()) {
            mViewModel.getUserInfo()
        } else {
            onNotLogin()
        }
    }

    //是否需要在OnResume中刷新数据，跳转到其他Activity页面返回需要刷新，增加这个标志位避免重复请求
    private var mNeedRefreshOnResume = false
    override fun onResume() {
        super.onResume()
        if (!mNeedRefreshOnResume) {
            mNeedRefreshOnResume = true
            return
        }
        initShowView()
        initData()

    }
    override fun onHiddenChanged(hidden: Boolean) {
        if (!hidden) {
            initShowView()
            initData()
        }
    }

    private fun onNotLogin() {
        mBinding.lUserInfo.visibility = View.GONE
        mBinding.btnLogin.visibility = View.VISIBLE
        mBinding.mineModel = null
        mBinding.lMedals.removeAllViews()

    }

    private fun onLogin() {
        mBinding.btnLogin.visibility = View.GONE
        mBinding.lUserInfo.visibility = View.VISIBLE
    }


    class ToolAdapter(
        private val mTabItem: List<TabItem>,
        private val onItemClick: (TabItem) -> Unit
    ) :
        RecyclerView.Adapter<ToolAdapter.ToolViewHolder>() {
        class ToolViewHolder(val binding: LayoutToolsItemBinding) :
            RecyclerView.ViewHolder(binding.root)

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ToolViewHolder {

            val binding =
                DataBindingUtil.inflate<LayoutToolsItemBinding>(
                    LayoutInflater.from(parent.context),
                    R.layout.layout_tools_item,
                    parent,
                    false
                )
            return ToolViewHolder(binding)
        }

        override fun onBindViewHolder(holder: ToolViewHolder, position: Int) {
            val binding = DataBindingUtil.getBinding<LayoutToolsItemBinding>(holder.itemView)
            binding?.let {
                binding.item = mTabItem[position]
                binding.vRedPoint.visibility =
                    if (mTabItem[position].hasNew) View.VISIBLE else View.GONE
            }
            holder.binding.lTab.setOnClickListener {
                onItemClick.invoke(mTabItem[position])
            }
        }

        override fun getItemCount(): Int = mTabItem.size
    }


    data class TabItem(
        val id: String,
        var tabName: String,
        var tabIcon: Int?,
        var hasNew: Boolean,
        var tabUrl: String? = null
    ) {
        fun requireIcon(): Any? {
            if (tabUrl != null) return tabUrl
            return tabIcon
        }
    }
}